package cn.linjianhui.flink.sample.web.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Component
@EnableScheduling
public class CacheExpireJob {
    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Value(value = "${flink-sample.cacheKey}")
    private String cacheKeys;

    @Scheduled(fixedRate = 1000*60*60)
    public void expire() {
        List<String> keys = new ArrayList<>();
        if(!StringUtils.isEmpty(cacheKeys)) {
            keys = Arrays.asList(cacheKeys.split(","));
        }

        for (String key : keys) {
            if(redisTemplate.hasKey(key)) {
                if (redisTemplate.getExpire(key) == -1) {
                    long todayTimestamp = LocalDateTime.now().toInstant(ZoneOffset.ofHours(8)).toEpochMilli();
                    long tomorrowTimestamp = LocalDate.now().plusDays(1).atStartOfDay(ZoneOffset.ofHours(8)).toInstant().toEpochMilli();
                    redisTemplate.expire(key, (tomorrowTimestamp - todayTimestamp) / 1000, TimeUnit.SECONDS);
                }
            }
        }
    }
}
